package com.agileai.portal.bizmoduler.forum;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManageImpl;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.portal.bizmoduler.uui.UserLocalManage;
import com.agileai.portal.extend.uui.UserSyncHelper;
import com.agileai.portal.wsclient.uui.ResultStatus;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.util.IOUtil;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class PostManageImpl
        extends TreeAndContentManageImpl
        implements PostManage {
    public PostManageImpl() {
        super();
        this.columnIdField = "COL_ID";
        this.columnParentIdField = "COL_PID";
        this.columnSortField = "COL_ORDERNO";
    }
    
	@Override
	public List<DataRow> findPostRecords(String moduleId,String postTypeCode,String postTypeId) {
		List<DataRow> result = null;
		String statementId = sqlNameSpace+".findPostRecords";
		String fpmExpression = null;
		String postType = null;
		String fpmReport = null;
		if("FPM_EXPRESSION".equals(postTypeId)){
			fpmExpression = postTypeCode;
		}else if("POST_TYPE".equals(postTypeId)){
			postType =postTypeCode;
		}else if("FPM_REPORT".equals(postTypeId)){
			fpmReport = postTypeCode;
		}else{
			//do nothing
		}
		DataParam param = new DataParam("moduleId",moduleId,"fpmExpression",fpmExpression,"postType",postType,"fpmReport",fpmReport);
		result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}

	@Override
	public List<DataRow> findPostRecordsBysearchWord(String searchWord) {
		List<DataRow> result = null;
		String statementId = sqlNameSpace+".findPostRecordsBysearchWord";
		DataParam param = new DataParam("searchWord",searchWord);
		result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}

	@Override
	public List<DataRow> findFavPostGrids(String userId) {
		List<DataRow> result = null;
		String statementId = sqlNameSpace+".findFavPostGrids";
		DataParam param = new DataParam("userId",userId);
		result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}

	@Override
	public Integer getFavCount(String userId) {
		String statementId = sqlNameSpace+".getFavCount";
		DataParam param = new DataParam("fuId",userId);
		DataRow row = this.daoHelper.getRecord(statementId, param);
		String countResult = row.get("countResult").toString();
		Integer result = Integer.valueOf(countResult);
		return result;
	}

	@Override
	public void deleteFavoriteRecord(String ffId) {
		String statementId = sqlNameSpace+"."+"deleteFavPostRecord";
		DataParam param = new DataParam("FF_ID",ffId);
		this.daoHelper.deleteRecords(statementId, param);
	}

	@Override
	public DataRow retrieveModuleInfo(String contentId) {
		String statementId = sqlNameSpace+"."+"retrieveModuleInfo";
		DataParam param = new DataParam("contentId",contentId);
		DataRow result = this.daoHelper.getRecord(statementId, param);
		return result;
	}

	@Override
	public List<DataRow> findPostTypes(String isNotAdmin,String isNotAdmin8Moderator) {
		List<DataRow> result = null;
		String statementId = sqlNameSpace+".findPostTypes";
		DataParam param = new DataParam("isNotAdmin",isNotAdmin,"isNotAdmin8Moderator",isNotAdmin8Moderator);
		result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}

	@Override
	public void updatePostMessageTop(String fpmId,String isTop) {
		String statementId = sqlNameSpace+"."+"updatePostMessageTop";
		DataParam param = new DataParam("FPM_ID",fpmId,"FPM_IS_TOP",isTop);
		this.daoHelper.updateRecord(statementId, param);
	}

	@Override
	public void updateSectionPostMessageTop(String fpmId,String isSectionTop) {
		String statementId = sqlNameSpace+"."+"updateSectionPostMessageTop";
		DataParam param = new DataParam("FPM_ID",fpmId,"FPM_SECTION_TOP",isSectionTop);
		this.daoHelper.updateRecord(statementId, param);
	}

	@Override
	public DataRow retrieveRepliesCount(String postId) {
		String statementId = sqlNameSpace+".retrieveRepliesCount";
		DataParam param = new DataParam("postId",postId);
		DataRow result = this.daoHelper.getRecord(statementId, param);
		return result;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public boolean sendNoticeMail(String userCode,String mailAddress,String category,String url,String title) {
		boolean result = false;
		try {
    		UserSync userSync = UserSyncHelper.getUserSyncService();
    		String tokenId = UserSyncHelper.genTokenId("sendMail");
    		String storeTokenId = String.valueOf(System.currentTimeMillis());
    		
			InputStream inputStream = PostManage.class.getResourceAsStream("PostTypeChange.ftl");
			ByteOutputStream byteOutputStream = new ByteOutputStream();
			IOUtil.copyAndCloseInput(inputStream, byteOutputStream);
			String templContent = new String(byteOutputStream.getBytes(),"UTF-8");
			
			HashMap model = new HashMap();
			model.put("title", title);
			model.put("postLink", url);
			String content = "";
			if("ESSENCE".equals(category)){
				content = "已经被评为精华帖";
			}else if("GARBAGE".equals(category)){
				content = "经其他用户举报,核实后确认你的帖子有违规信息,此贴已被评为垃圾帖";
			}else if("KEY".equals(category)){
				content = "已经被评为重点帖";
			}else if("ORDINARY".equals(category)){
				content = "已经被评为精华帖";
			}
			model.put("content", content);
			
			StringWriter writer = new StringWriter();
			generate(templContent, model, writer, "UTF-8");
    		String mailContent = writer.toString();
    		mailContent = mailContent.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
    		
			String mailSubject = "数通畅联--帖子类型变更通知";
			ResultStatus resultStatus = userSync.sendMail(tokenId, mailAddress, mailSubject, mailContent);
			if (resultStatus.isSuccess()){
				Date storeTokenTime = new Date();
				UserLocalManage userLocalManage = this.lookupService(UserLocalManage.class);
				userLocalManage.updateUserTokends(userCode, storeTokenId, storeTokenTime);	
				result = true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static void generate(String templContent,Object model,Writer writer,String encoding) {
		try {
        	Configuration cfg = new Configuration();
        	cfg.setTemplateLoader(new StringTemplateLoader(templContent));  
        	cfg.setEncoding(Locale.getDefault(), encoding);
            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        	Template temp = cfg.getTemplate("");
        	temp.setEncoding(encoding);
            Map root = new HashMap();
            root.put("model",model);
            temp.process(root, writer);
            writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<DataRow> findPostRecordsNotTop(String moduleId,
			String postTypeCode, String postTypeId) {
		List<DataRow> result = null;
		String statementId = sqlNameSpace+".findPostRecordsNotTop";
		String fpmExpression = null;
		String postType = null;
		String fpmReport = null;
		if("FPM_EXPRESSION".equals(postTypeId)){
			fpmExpression = postTypeCode;
		}else if("POST_TYPE".equals(postTypeId)){
			postType =postTypeCode;
		}else if("FPM_REPORT".equals(postTypeId)){
			fpmReport = postTypeCode;
		}else{
			//do nothing
		}
		DataParam param = new DataParam("moduleId",moduleId,"fpmExpression",fpmExpression,"postType",postType,"fpmReport",fpmReport);
		result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}

	
	
}